package controller;

import dao.EmployeeDAO;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import model.Employee;
import model.User;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

@WebServlet("/EmployeeServlet")
public class EmployeeServlet extends HttpServlet {
    private EmployeeDAO employeeDAO = new EmployeeDAO();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        if (action == null) action = "list";

        switch (action) {
            case "list":
                listEmployees(request, response);
                break;
            case "view":
                viewEmployee(request, response);
                break;
            case "add":
                request.getRequestDispatcher("/employee/add.jsp").forward(request, response);
                break;
            case "edit":
                editEmployee(request, response);
                break;
            case "delete":
                deleteEmployee(request, response);
                break;
            case "search":
                searchEmployees(request, response);
                break;
            default:
                listEmployees(request, response);
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        if (action.equals("add")) {
            addEmployee(request, response);
        } else if (action.equals("edit")) {
            updateEmployee(request, response);
        }
    }

    // 列表显示所有员工
    private void listEmployees(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<Employee> employees = employeeDAO.getAllEmployees();
        request.setAttribute("employees", employees);
        request.getRequestDispatcher("/employee/list.jsp").forward(request, response);
    }

    // 查看单个员工
    private void viewEmployee(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Employee employee = employeeDAO.getEmployeeById(id);
        request.setAttribute("employee", employee);
        request.getRequestDispatcher("/employee/view.jsp").forward(request, response);
    }

    // 添加员工
    private void addEmployee(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        Employee employee = new Employee();
        try {
            employee.setName(request.getParameter("name"));
            employee.setDepartment(request.getParameter("department"));
            employee.setPosition(request.getParameter("position"));
            employee.setSalary(new BigDecimal(request.getParameter("salary")));
            employee.setEmail(request.getParameter("email"));
            employee.setPhone(request.getParameter("phone"));
            employee.setHireDate(sdf.parse(request.getParameter("hireDate")));
            employee.setCreatedBy(loginUser.getId());

            boolean success = employeeDAO.addEmployee(employee);
            if (success) {
                response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list");
            } else {
                request.setAttribute("errorMsg", "添加员工失败！");
                request.getRequestDispatcher("/employee/add.jsp").forward(request, response);
            }
        } catch (ParseException e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "日期格式错误！");
            request.getRequestDispatcher("/employee/add.jsp").forward(request, response);
        }
    }

    // 编辑员工（跳转页面）
    private void editEmployee(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Employee employee = employeeDAO.getEmployeeById(id);
        request.setAttribute("employee", employee);
        request.getRequestDispatcher("/employee/edit.jsp").forward(request, response);
    }

    // 更新员工
    private void updateEmployee(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            Employee employee = new Employee();
            employee.setId(Integer.parseInt(request.getParameter("id")));
            employee.setName(request.getParameter("name"));
            employee.setDepartment(request.getParameter("department"));
            employee.setPosition(request.getParameter("position"));
            employee.setSalary(new BigDecimal(request.getParameter("salary")));
            employee.setEmail(request.getParameter("email"));
            employee.setPhone(request.getParameter("phone"));
            employee.setHireDate(sdf.parse(request.getParameter("hireDate")));

            boolean success = employeeDAO.updateEmployee(employee);
            if (success) {
                response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list");
            } else {
                request.setAttribute("errorMsg", "更新员工失败！");
                request.getRequestDispatcher("/employee/edit.jsp").forward(request, response);
            }
        } catch (ParseException e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "日期格式错误！");
            request.getRequestDispatcher("/employee/edit.jsp").forward(request, response);
        }
    }

    // 删除员工
    private void deleteEmployee(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        employeeDAO.deleteEmployee(id);
        response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list");
    }

    // 多条件查询
    private void searchEmployees(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter("name");
        String department = request.getParameter("department");
        String position = request.getParameter("position");

        List<Employee> employees = employeeDAO.searchEmployees(name, department, position);
        request.setAttribute("employees", employees);
        request.setAttribute("searchParams", request.getParameterMap()); // 回显查询条件
        request.getRequestDispatcher("/employee/list.jsp").forward(request, response);
    }
}
